import Taro, { Component } from '@tarojs/taro'
import { AtForm, AtButton } from 'taro-ui'
import { View, Image, Text } from '@tarojs/components'
import { DNavBar, DImagesupload } from '@/components'
import _dayjs from 'dayjs'
import http from '@/api'
import './dwaitinventory.scss'

const addressIcon = require('../../assets//images/address.png')
const locationIcon = require('../../assets//images/location.png')
export default class dwaitinventory extends Component {

  constructor(props) {
    super(props)
    this.state = {
      active: 0,
      date: _dayjs().format('YYYY-MM-DD HH:mm:ss'),
      carStocktaking: {},
      address: '',
      id: '',
      outPic: ['车辆正面', '车辆侧面', '车辆背面'],
      inPic: ['车辆仪表盘'],
      carInfo: ['铭牌或车架号'],
      fileImg: [],
    }
  }
  async componentWillMount() {
    const { searchInfo: address } = await this.loadScript()
    this.setState({
      id: this.$router.params.id,
      address
    })
  }

  handleClick(value) {
    this.setState({
      active: value
    })
  }

  onSubmit() {
    // let { carStocktaking } = this.state
    let { address, date, id, fileImg } = this.state
    let addStocktakingDetail = {
      address,
      date,
      refInfoId: this.$router.params.refInfoId,
      id: this.$router.params.id,
      carStocktakingFiles: fileImg
    }
    if (addStocktakingDetail.carStocktakingFiles.length === 0) {
      Taro.showToast({
        title: '请填写完整信息',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    http.putAppStocktaking(addStocktakingDetail).then(res => {
      Taro.showToast({
        title: '提交成功',
        duration: 800
      }).then(() => {
        Taro.navigateBack({
          delta: 1
        })
      })
    })
  }

  onChangeImages(typeId, id, list) {
    const { outPic, inPic, carInfo, fileImg } = this.state
    let arr = []
    let title = []
    if (typeId === 1) {
      title = outPic
    } else if (typeId === 2) {
      title = inPic
    } else if (typeId === 3) {
      title = carInfo
    }
    list.forEach((item, index) => {
      let obj = {}
      obj['imgAliyunUrl'] = `${item.url}`,
        obj['imgTitle'] = `${typeId === 4 ? '' : title[id]}`,
        obj["imgType"] = typeId,
        // obj["refDetailId"] = this.$router.params.refDetailId
        obj["sort"] = 1
      if (typeId === 4) {
        fileImg.push(obj)
      } else {
        if (fileImg.length != 0) {
          for (let i = 0; i < fileImg.length; i++) {
            if (fileImg[i].imgTitle == obj.imgTitle) {
              fileImg[i] = obj
            }
            if (i + 1 === fileImg.length && fileImg[i].imgTitle !== obj.imgTitle) {
              fileImg.push(obj)
            }
          }
        } else {
          fileImg.push(obj)
        }
      }
    })

    this.setState({
      fileImg
    })
  }

  onLookImages(status = '') {
    Taro.navigateTo({
      url: `/pages/itemImages/itemImages?status=${status}`
    })
  }
  //异步加载地图库函数文件
  loadScript(info) {
    const _that = this
    return new Promise((res, rej) => {
      window.__init__ = () => {
        // 百度地图API功能
        const map = new BMap.Map("container_map");
        let searchInfo = '';
        //获取当前坐标
        new BMap.Geolocation().getCurrentPosition(
          function (r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
              let currentIp = r.point
              _that.setState({
                currentIp: currentIp
              }, () => {
              })
              let addr = r.address
              searchInfo += addr.province;
              searchInfo += addr.city;
              searchInfo += addr.district;
              searchInfo += addr.street;
              searchInfo += addr.street_number;

              res({
                map,
                searchInfo
              })
            }
          },
          { enableHighAccuracy: true }
        );
      }
      //创建script标签
      var script = document.createElement("script");
      //设置标签的type属性
      script.type = "text/javascript";

      //设置标签的链接地址
      script.src = "//api.map.baidu.com/api?v=2.0&ak=ePq0Qz5lmCsQgyLzu4DHaDxg0YPpLBuk&callback=__init__&time=" + new Date().getTime();
      //添加标签到dom
      document.body.appendChild(script);
    })
  }
  // 获取定位
  location() {
    const _that = this
    Taro.showLoading()
    const map = new BMap.Map("container_map");
    let searchInfo = '';
    //获取当前坐标
    new BMap.Geolocation().getCurrentPosition(
      function (r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          let currentIp = r.point

          let addr = r.address
          searchInfo += addr.province;
          searchInfo += addr.city;
          searchInfo += addr.district;
          searchInfo += addr.street;
          searchInfo += addr.street_number;
          _that.setState({ address: searchInfo }, () => {
            Taro.hideLoading()
          })
        }
      },
      { enableHighAccuracy: true }
    )
  }

  render() {
    const {
      date,
      outPic,
      inPic,
      carInfo,
      address
    } = this.state
    return (
      <View className='b_dwaitinventory'>
        <DNavBar title={'待盘库'} className='b_dwaitinventory_nav'></DNavBar>
        <View className='b_dwaitinventory__box'>
          {/* <View className='b_dwaitinventory__box_flex'>
            <View className='b_dwaitinventory__box_left'>
              <View>地点</View>
              <View>时间</View>
            </View>
            <View className='b_dwaitinventory__box_right'>
              <View className='b_dwaitinventory__box_right_flex'>
                <View>
                  {address}
                </View>
                <View>
                  <Image src={map} className='b_dwaitinventory__box_right_img' onClick={this.location.bind(this)}></Image>
                </View>
              </View>
              <View>{date}</View>
            </View>
          </View> */}
          {/* <Text>请上传以下验车照片</Text> */}
          <View className='b_dwaitinventory__form'>
            <AtForm>
              <View className='b_dwaitinventory__form__item'>
                {/* <Text className='at-icon-star_'></Text> */}
                <View className='b_dwaitinventory__form_title'>请上传以下验车照片</View>
                <View className='b_dwaitinventory__images'>
                  <Text className="b_dwaitinventory__images_title"><Text className='at-icon-star_'></Text>车辆外观</Text>
                  {/* <Text className="b_dwaitinventory__images_tips" onClick={this.onLookImages.bind(this, 'carout')}>查看范例</Text> */}
                  <View style='display:flex;justify-content:space-between'>
                    <DImagesupload count={1} text={'查看'} isWatermark onChangeImages={this.onChangeImages.bind(this, 1, 0)}></DImagesupload>
                    <DImagesupload count={1} text={'查看'} isWatermark onChangeImages={this.onChangeImages.bind(this, 1, 1)}></DImagesupload>
                    <DImagesupload count={1} text={'查看'} isWatermark onChangeImages={this.onChangeImages.bind(this, 1, 2)}></DImagesupload>
                    {/* <DImagesupload count={1} text={'查看'} onChangeImages={this.onChangeImages.bind(this, 1, 3)}></DImagesupload> */}
                  </View>
                  <View style='display:flex;justify-content:space-between'>
                    {outPic && outPic.map(item => {
                      return <Text >{item}</Text>
                    })
                    }
                  </View>

                </View>
                <View className='b_dwaitinventory__images'>
                  {/* <Text className="b_dwaitinventory__images_tips" onClick={this.onLookImages.bind(this, 'carinside')}>查看范例</Text> */}
                  <Text className="b_dwaitinventory__images_title"><Text className='at-icon-star_'></Text>车内照片</Text>
                  <View style='display:flex;'>
                    <View style='margin-right:15px'><DImagesupload count={1} isWatermark onChangeImages={this.onChangeImages.bind(this, 2, 0)}></DImagesupload></View>
                    {/* <View style='margin-right:15px'><DImagesupload count={1} onChangeImages={this.onChangeImages.bind(this, 2, 1)}></DImagesupload></View> */}
                  </View>
                  <View style='display:flex;'>
                    {inPic && inPic.map(item => {
                      return <Text style='margin-right:35px'>{item}</Text>
                    })
                    }
                  </View>
                </View>
                <View className='b_dwaitinventory__images'>
                  {/* <Text className="b_dwaitinventory__images_tips" onClick={this.onLookImages.bind(this, 'carinfo')}>查看范例</Text> */}
                  <Text className="b_dwaitinventory__images_title"><Text className='at-icon-star_'></Text>车辆信息</Text>
                  <View style='display:flex;'>
                    <View style='margin-right:15px'><DImagesupload isWatermark count={1} onChangeImages={this.onChangeImages.bind(this, 3, 0)}></DImagesupload></View>
                    {/* <View style='margin-right:15px'><DImagesupload count={1} onChangeImages={this.onChangeImages.bind(this, 3, 1)}></DImagesupload></View> */}
                  </View>
                  <View style='display:flex;'>
                    {carInfo && carInfo.map(item => {
                      return <Text style='margin-right:30px'>{item}</Text>
                    })
                    }
                  </View>
                </View>
                <View className='b_dwaitinventory__images'>
                  <Text className="b_dwaitinventory__images_title">异常照片(如车辆异常，请上传照片)</Text>
                  <DImagesupload isWatermark onChangeImages={this.onChangeImages.bind(this, 4, '')} count={8}></DImagesupload>
                </View>
                <View className='b_dwaitinventory__box_right_flex'>
                  <Image src={addressIcon} className='b_dwaitinventory__box_right_img' onClick={this.location.bind(this)}></Image>
                  <View className='address_con'>{address}</View>
                  <Image src={locationIcon} className='b_dwaitinventory__box_right_img' onClick={this.location.bind(this)}></Image>
                </View>
              </View>
            </AtForm>
          </View>
          <View className='b_dwaitinventory__footer'>
            <AtButton className='item_btn' onClick={this.onSubmit.bind(this)}>确认提交</AtButton>
          </View>
        </View>
      </View>

    )
  }

}
